<template>
  <van-nav-bar title="食材识别" left-text="返回" left-arrow @click-left="onClickLeft" />

  <div class="pic">
    <van-uploader v-model="fileList" multiple :max-count="1" :preview-size="['9.16rem', '7.46rem']"
      @change="handleFileChange(fileList)" :after-read="handleAfterRead" />
    <van-button v-if="fileList.length > 0 && !loading && !result" type="primary" size="large"
      @click="onRecognize">开始识别</van-button>
    <van-loading type="spinner" vertical size="36px" v-if="loading">识别中...</van-loading>
  </div>
  <!-- <ingredients v-if="result" :data="resultData" /> -->
  <!-- <ingredients></ingredients> -->

  <div v-if="result">
    <div class="title">
      <div class="name">{{ resultData.name }}</div>
      <div class="match">
        <div class="progress">
          <div class="bar" :style="{ width: resultData.match }"></div>
        </div>
        <div class="match-info">
          {{ resultData.match }}匹配度
        </div>
      </div>
      <div class="other">
        <div class="first">
          {{ resultData.similar[0] }}
        </div>
        <div class="second">
          {{ resultData.similar[1] }}
        </div>
      </div>
    </div>

    <div class="menu-content">
      <ul class="select">
        <li @click="change('nutrition')" :class="{ active: flag === 'nutrition' }">营养成分</li>
        <li @click="change('tips')" :class="{ active: flag === 'tips' }">健康提示</li>
        <li @click="change('storage')" :class="{ active: flag === 'storage' }">存储方法</li>
      </ul>
      <div class="content">
        <div v-if="flag === 'nutrition'" class="content-part">
          <ul>
            <li v-for="(value, key) in resultData.nutrition">
              <div class="part">{{ key }}</div>
              <div class="value">{{ value }}</div>
            </li>
          </ul>
        </div>
        <div v-if="flag === 'tips'" class="content-tips">
          {{ resultData.tips }}
        </div>
        <div v-if="flag === 'storage'" class="content-store">
          {{ resultData.store }}
        </div>
      </div>

    </div>

    <div class="recommend">
      <div class="topic">推荐菜谱</div>
      <div class="content-parts">
        <div @click="goToEditCook(item)" v-for="item in resultData?.recommend" class="card">
          <div class="pic">
            <img :src="item.image" :alt="item.name">
          </div>
          <div class="contents">
            <h2>{{ item.name }}</h2>
            <p>{{ item.desc }}</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import router from '@/router/index.js'
// import ingredients from '@/components/ingredients.vue'
import { onMounted, ref, watch } from 'vue'
import { main } from '@/utils/foodRecognize.js'
import { showSuccessToast } from 'vant'
import { generateImg } from '@/api/index.js'

const goToEditCook = (item) => {
  router.push({
    path: '/editCook',
    query: {
      dishName: item.name,
      image: item.image,
      desc: item.desc
    }
  });
  result.value = false;
}

const onClickLeft = () => {
  router.back()
}

const fileList = ref([]);
const result = ref(false);
const loading = ref(false);
const resultData = ref(null);
const flag = ref('nutrition'); // 默认显示营养成分

const change = (item) => {
  flag.value = item
}

// 将文件转换为Base64
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

// 当文件列表发生变化时调用此函数
const handleFileChange = (files) => {
  if (files.length === 0) {
    // 如果文件列表为空，则重置所有状态
    result.value = false;
    loading.value = false;
    resultData.value = null;
  }
}

// 处理文件读取完成后的逻辑，确保在识别过程中不触发
const handleAfterRead = (file) => {
  if (!loading.value) {
    fileList.value = [file];
  }
}


// const onRecognize = async () => {
//   if (fileList.value.length === 0) return;

//   loading.value = true;

//   try {
//     const base64Image = await getBase64(fileList.value[0].file);
//     const res = await main(base64Image);

//     // 清理并解析JSON字符串
//     let jsonString = res.replace(/^```json\s*|\s*```\s*$/g, '').trim();
//     const data = JSON.parse(jsonString);

//     // 👇 STEP 1：先渲染页面
//     resultData.value = data;
//     result.value = true;
//     loading.value = false;
//     showSuccessToast('识别完成');

//     console.log(resultData.value);

//     let imgArr = []
//     for (let i = 0; i < data.recommend.length; i++) {
//       let imgUrl = await generateImg(`${data.recommend[i].name}`, "1024x1024");
//       imgArr[i] = imgUrl
//     }
//     for (let i = 0; i < data.recommend.length; i++) {
//       resultData.value.image = imgArr[i]
//     }

//   } catch (error) {
//     console.error('识别或处理失败', error);
//     loading.value = false;
//   }
// }


// const onRecognize = async () => {
//   if (fileList.value.length > 0) {
//     loading.value = true;
//     try {
//       // 获取Base64编码的图片数据
//       const base64Image = await getBase64(fileList.value[0].file);

//       // 调用main函数并传入Base64图像数据
//       const res = await main(base64Image);

//       // 假设res是一个包含多余标记的JSON字符串
//       let jsonString = res;

//       // 去除```json开头和结尾的```以及换行符
//       jsonString = jsonString.replace(/^```json\s*|\s*```\s*$/g, '').trim();

//       // 将清理后的字符串解析为JSON对象
//       const data = JSON.parse(jsonString);

//       // console.log(data); // 现在data是一个JavaScript对象
//       for (let i = 0; i < data.recommend.length; i++) {
//         try {
//           let imgUrl = await generateImg(`${data.recommend[i].name}`, "1024x1024")
//           data.recommend[i].image = imgUrl.url
//         } catch (error) {
//           // data.recommend[0].image = 'https://aigc-files.bigmodel.cn/api/cogview/20250307234654dbe9f158df4a4a1f_0.png'
//           // data.recommend[1].image = 'https://aigc-files.bigmodel.cn/api/cogview/2025030723280738ffa5d7c4e14afa_0.png'
//           console.log("图片生成失败");
//         }
//       }
//       resultData.value = data;
//       loading.value = false;
//       showSuccessToast('识别完成')
//       result.value = true;
//     } catch (error) {
//       console.error('There was an error uploading the image!', error);
//     }
//   }
// }

const onRecognize = async () => {
  if (fileList.value.length === 0) return;

  loading.value = true;

  try {
    const base64Image = await getBase64(fileList.value[0].file);
    const res = await main(base64Image);

    // 清理并解析JSON字符串
    let jsonString = res.replace(/^```json\s*|\s*```\s*$/g, '').trim();
    const data = JSON.parse(jsonString);

    // 👇 STEP 1：先渲染基础数据（不带图片）
    resultData.value = data;
    result.value = true;
    loading.value = false;
    showSuccessToast('识别完成');

    // 👇 STEP 2：异步加载推荐菜谱的图片
    const newRecommend = [...data.recommend]; // 创建 recommend 的副本

    for (let i = 0; i < newRecommend.length; i++) {
      try {
        const imgUrl = await generateImg(`${newRecommend[i].name}`, "1024x1024");

        // 更新当前项，并加上 image 字段
        newRecommend[i] = {
          ...newRecommend[i],
          image: imgUrl.url
        };
      } catch (err) {
        console.error(`生成图片失败：${newRecommend[i].name}`, err);
      }
    }

    // 最后一次性替换整个 recommend 数组，确保 Vue 响应式更新
    resultData.value = {
      ...data,
      recommend: newRecommend
    };

  } catch (error) {
    console.error('识别或处理失败', error);
    loading.value = false;
  }
}
</script>

<style lang="less" scoped>
.pic {
  margin: 0.42rem;
}

/* 当loading为true时，禁用uploader */
.disabled .van-uploader__wrapper {
  display: none; // 隐藏整个uploader区域
}

/* 或者使用pointer-events: none来禁止点击 */
.disabled .van-uploader__input-wrapper {
  pointer-events: none;
  opacity: 0.5; // 可选：降低透明度以示不可用
}


.title {
  margin: 24px 16px;
  padding: 16px;
  background: #FFFFFF;
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
  border-radius: 12px;

  .name {
    font-weight: 500;
    font-size: 24px;
    color: #1F2937;
    margin-bottom: 14px;
  }

  .match {
    display: flex;
    align-items: center;

    .progress {
      height: 8px;
      background-color: #E5E7EB;
      border-radius: 4px;
      width: 6rem;
      overflow: hidden;

      .bar {
        background-color: #4CAF50;
        height: 100%;
      }
    }

    .match-info {
      font-weight: 400;
      font-size: 14px;
      color: #4B5563;
      margin-left: 16px;
    }
  }

  .other {
    display: flex;
    align-items: center;
    margin-top: 16px;

    div {
      padding: 8px 13px;
      background: rgba(249, 115, 22, 0.1);
      border-radius: 4px;
      border: 1px solid #E5E7EB;
      font-weight: 400;
      font-size: 14px;
      color: #F97316;
      margin-right: 8px;
    }
  }

}

.menu-content {
  background-color: #FFF;
  margin: 0 16px;
  border-bottom: 1px solid #E5E7EB;


  .select {
    display: flex;
    justify-content: space-between;

    li {
      padding: 15px 29px;
      font-weight: 400;
      font-size: 14px;
      color: #4B5563;
    }

    .active {
      color: #4CAF50;
      border-bottom: 3px solid #4CAF50;
    }
  }

  .content {
    height: 4rem;


    .content-part {
      height: 4rem;

      ul {
        padding: 16px;

        li {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 16px;
          font-weight: 400;
          font-size: 14px;
          color: #4B5563;
        }
      }
    }

    .content-tips {
      padding: 16px;
      height: 4rem;
      font-weight: 400;
      font-size: 14px;
      color: #4B5563;
      line-height: 22px;
      box-sizing: border-box;
    }

    .content-store {
      padding: 16px;
      height: 4rem;
      font-weight: 400;
      font-size: 14px;
      color: #4B5563;
      line-height: 22px;
      box-sizing: border-box;
    }
  }
}

.recommend {
  margin: 16px;

  .topic {
    margin-bottom: 16px;
    font-weight: 500;
    font-size: 18px;
    color: #1F2937;
  }

  .content-parts {
    display: flex;
    justify-content: space-around;

    .card {
      width: 4rem;
      background: #FFFFFF;
      padding-bottom: 16px;
      box-sizing: border-box;


      .pic {
        width: 100%;
        margin: 0;

        img {
          width: 100%;
          height: auto;
          border-radius: 12px;
        }
      }

      .contents {
        h2 {
          font-size: 0.38rem;
          color: #000000;
          font-weight: 500;
          margin: 8px 0;
          display: flex;
          align-items: center;
        }
      }

      p {
        font-weight: 400;
        font-size: 12px;
        color: #6B7280;
      }
    }
  }
}
</style>